/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.shop.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.core.constant.enums.BooleanTypeEnum;
import com.pig4cloud.pigx.common.core.constant.enums.DeleteFlagEnum;
import com.pig4cloud.pigx.shop.user.api.entity.ShopUserAddress;
import com.pig4cloud.pigx.shop.user.mapper.ShopUserAddressMapper;
import com.pig4cloud.pigx.shop.user.service.ShopUserAddressService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户地址
 *
 * @author pigx code generator
 * @date 2023-12-03 22:42:40
 */
@Service
public class ShopUserAddressServiceImpl extends ServiceImpl<ShopUserAddressMapper, ShopUserAddress>
		implements ShopUserAddressService {

	/**
	 * c端添加用户地址
	 * @param shopUserAddress
	 * @return
	 */
	@Override
	public boolean add(ShopUserAddress shopUserAddress) {
		updateDefaultAddress(shopUserAddress);
		this.save(shopUserAddress);
		return true;
	}

	/**
	 * c端更新用户地址
	 * @param shopUserAddress
	 * @return
	 */
	@Override
	public boolean update(ShopUserAddress shopUserAddress) {
		updateDefaultAddress(shopUserAddress);
		this.updateById(shopUserAddress);
		return false;
	}

	/**
	 * 修改默认地址
	 * @param shopUserAddress
	 */
	private void updateDefaultAddress(ShopUserAddress shopUserAddress) {
		// 设置了默认地址的场合
		if (shopUserAddress.getIsDefault().equals(BooleanTypeEnum.TRUE.getType())) {
			LambdaQueryWrapper<ShopUserAddress> lqwShopUserAddress = new LambdaQueryWrapper<>();
			lqwShopUserAddress.eq(ShopUserAddress::getShopUserId, shopUserAddress.getShopUserId());
			lqwShopUserAddress.eq(ShopUserAddress::getDelFlag, DeleteFlagEnum.VALID.getType());
			List<ShopUserAddress> list = this.list(lqwShopUserAddress);
			list.forEach(item -> {
				item.setIsDefault(BooleanTypeEnum.FALSE.getType());
			});
			this.updateBatchById(list);
		}
	}

}
